//
//  LHLandingViewController.swift
//  LHWeibo
//
//  Created by 李浩 on 16/4/6.
//  Copyright © 2016年 李浩. All rights reserved.
//

import UIKit
import AFNetworking

class LHLandingViewController: UIViewController,UIWebViewDelegate {

    //创建一个webView的实例 让它填充到视图里
    
     let webView : UIWebView = UIWebView()
    
    
    
    override func loadView() {
        
        view = webView
        
        //设置代理
        
        
        webView.delegate = self
        
        
        setNavItem()
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

       
        view.backgroundColor = UIColor.whiteColor()
        

        //设置webView的显示的内容 
        
        //拼接字符串
        
         let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(AppURL)"
        
        
        
        let url = NSURL(string: urlStr)
        
        if let url = url {
        
            let reuqeue = NSURLRequest(URL: url)
        
        
            webView.loadRequest(reuqeue)
        }
        
        
        
        
    }

    
    func setNavItem(){
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action:"dismantle")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "padding")
        
        
        
    }

    
    func dismantle(){
    
    
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    
    
    }

    
    
    func padding(){
    
        print("自动填充")
    
        
         let js = "document.getElementById(\"userId\").value = \"15711162966\";document.getElementById(\"passwd\").value = \"qaz123..0\""
        
        
        
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    
    
    }

    
    //所有的网络请求都会走这个方法
    //如果返回值 为true 则允许网络请求继续
    
    //如果返回值为false 不允许网络请求
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request)
        
        /**
        *     absoluteString: 绝对路径
              relativeString: 相对路径
        */
        
        
        if let absoluteStr = request.URL?.absoluteString {
        
        
            //通过判断字符串的前缀来区别 
            
            if absoluteStr.hasPrefix(AppURL){
            
                guard let code = request.URL?.query else{
                
                
                    return true
                }
            
            
                //截取字符串
                
                let substr = code.substringFromIndex("code=".endIndex)
                
                print(substr)
                
                // 发送一个请求.来获取Token
                getToken(substr)
                
            }
            
        
        
        
        
        }
        
        
        
        
        
        return true
    }
    
    
    //创建一个网络请求 来获取Token 
    
    
    func getToken(code:String){
    
        
        
        let afn = AFHTTPSessionManager()
        
        
        // 设置 afn contentType
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        let parameters = ["client_id": AppKey,
            
            "client_secret": AppSecret,
            "grant_type":"authorization_code",
            "code" :code,
            "redirect_uri":AppURL
        
        
        
        ]
        
        
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: parameters, progress: nil, success: { (_,JSON ) -> Void in
            
            
            //判断可选项 并且需要转换成字典
            
            guard let json = JSON as? [String :NSObject] else{
            
            
                return
            
            
            }
            
            let urseModel = LHUrseModel(dic: json)
            
            //获取token值 在去发送一个网络请求 来获取个人信息
            
             // 为什么用self -> success里 是闭包
            self.getUseInfo(urseModel)
            
        
            }) { (_, error) -> Void in
                
                
                print(error);
                
        }
    
    
    
    
    }
    
    
    
    func getUseInfo(urseModel : LHUrseModel){
    
        
        let afn = AFHTTPSessionManager()
        
        
        // 设置 afn contentType
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //拼接参数
    
        guard let token = urseModel.access_token,uid = urseModel.uid else{
        
        
            return
        
        
        }
        
        let parmes = [
        
            "access_token":token,
            "uid":uid
        
        
        ]
        
    
        afn.GET("https://api.weibo.com/2/users/show.json", parameters: parmes, progress: nil, success: { (_, JSON) -> Void in
        
            print(JSON)
            
            guard let json = JSON as? [String :NSObject] else {
            
                return
            
            }
            
            
            //登陆成功退出界面
            self.dismissViewControllerAnimated(true, completion: nil)
            
            
            urseModel.name = json["name"] as! String?
         
            
            urseModel.avatar_large = json["avatar_large"] as! String?
            
            
            let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("urse.plist")
            
            //归档
            
            NSKeyedArchiver.archiveRootObject(urseModel, toFile: path)
            
            print(path)
            
            
            
            
            }) { (_, error) -> Void in
            
                
                print(error)
                
                
        }
    
    }
    
    
    
    

}
